from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
import json
import requests
import time
from bs4 import BeautifulSoup
import time
import re
import urllib


#返回结果格式
def resultData():
    data = {
        "websiteType" : 0,
        "titleName":"",
        "titleHref": "",
        "source":"",
        "label":"",
        "volume":"",
        "summary":"",
        "detailId":'',
        "publishTime" :"",
        "category" : "",
        "quote" :"",
        "abstract": "",
        "doi": "",
        "downLoad": "",
        "keyword": [],
        "author": [],

    }
    return data

def formData(response):
    allData = []

    lis = response.json()['finalDt']['Values']

    for li in lis:
        tempData = resultData()

        try:
            tempData["titleName"] = li[11]
        except:
            pass
        try:
            tempData["titleHref"] = "https://www.lieguozhi.com/skwx_lgz/" + li[1]
        except:
            pass
        try:
            tempData["author"] = [li[5]]
        except:
            pass
        try:
            tempData["source"] = li[4]
        except:
            pass
        try:
            tempData["publishTime"] = li[6]
        except:
            pass
        try:
            tempData["keyword"] = [li[12]]
        except:
            pass

        allData.append(tempData)


    return allData

def getData(keyword):

    headers = {
        'Origin': 'https://www.lieguozhi.com',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.8',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.104 Safari/537.36',
        'Content-type': 'application/x-www-form-urlencoded',
        'Accept': '*/*',
        'Referer': 'https://www.lieguozhi.com/skwx_lgz/search?query=ax&search=1&SiteID=45&searchType=all&detailtype=All',
        'Connection': 'keep-alive',
    }

    data = {
        '_ZVING_METHOD': 'lgzgeneral.bindList',
        '_ZVING_DATA': '{"area":"","years":"","orderBy":"","resourceType":"","query":"ax","siteId":"45","pageIndex":"0","OrderBy":"","pageSearchType":"all","pageType":"","index":"0","searchType":"","type":"all","search":"1","titleSecond":"","authorSecond":"","keyWordSecond":"","beginTimeSecond":"","endTimeSecond":"","searchSecond":"","detailType":"All","keyWords":"","author":"","ltt":"","oltt":""}',
        '_ZVING_URL': '/skwx_lgz/search'
    }

    response = requests.post('https://www.lieguozhi.com/skwx_lgz//ajax/invoke', headers=headers, data=data)


    allData = formData(response)


    return allData


def index(request):

    data = json.loads(request.POST.get('data', '1'))

    allData = getData(data["values"][0])

    return HttpResponse(json.dumps({
        "collection": allData,
        "allNum": 0
    }), content_type="application/json")